package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.Websocket.WebSocketServer;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingMapper shoppingMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        //异常处理：1购物车不能为空，2.地址簿不能为空
        List<ShoppingCart> list = shoppingMapper.checkShoppingCart(BaseContext.getCurrentId());
        if(list.isEmpty()){
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //插入到订单表中
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //将相关信息补充完整
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        String address=addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDetail();
        orders.setAddress(address);
        BeanUtils.copyProperties(addressBook,orders);
        //插入到表中
        orderMapper.insert(orders);
        //
        OrderDetail orderDetail=new OrderDetail();

        List<ShoppingCart> shoppingCarts = shoppingMapper.checkShoppingCart(orders.getUserId());
        for (ShoppingCart shoppingCart : shoppingCarts) {
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailMapper.insert(orderDetail);
        }
        //清空购物车
        shoppingMapper.clean(orders.getUserId());
        //返回数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        // 替代微信支付成功后的数据库订单状态更新，直接在这里更新了
        // 根据订单号查询当前用户的该订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders=new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPayStatus(Orders.PAID);
        orders.setCheckoutTime(LocalDateTime.now());
//        Orders orders = Orders.builder()
//                .id(ordersDB.getId())
//                .status(Orders.TO_BE_CONFIRMED) // 订单状态，待接单
//                .payStatus(Orders.PAID) // 支付状态，已支付
//                .checkoutTime(LocalDateTime.now()) // 更新支付时间
//                .build();

        orderMapper.update(orders);
        //通过websocket发送消息
        Map<String, Object> map = new HashMap<>();
        map.put("type",1);//1表示来单提醒
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+ordersPaymentDTO.getOrderNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

        return vo;
    }


    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        //通过websocket发送消息
        Map<String, Object> map = new HashMap<>();
        map.put("type",1);//1表示来单提醒
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+outTradeNo);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    @Override
    public PageResult getHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //调用PageHelper插件
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //调用函数
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<OrderVO> p=orderMapper.getBuyUserId(ordersPageQueryDTO);
        //封装解析
        for (OrderVO orderVO : p) {
            orderVO.setOrderDetailList(orderDetailMapper.getByOrderId(orderVO.getId()));
        }
        return new PageResult(p.getTotal(),p.getResult());
    }

    @Override
    public OrderVO getOrderDetail(Long id) {
        //先查订单表
        OrderVO orderVO =orderMapper.getId(id);
        //在查订单详情表
        List<OrderDetail> list=orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    @Override
    public void cancelById(Long id) {
        //先判断id是否存在
        OrderVO orderVO = orderMapper.getId(id);
        Orders build = Orders.builder().id(id).status(Orders.CANCELLED).build();
        if(orderVO==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //如果订单状态为未接单则可以直接取消
        if(orderVO.getStatus()>2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //如果订单状态未已支付，则需退款
        if(orderVO.getPayStatus()==Orders.PAID){
            System.out.println("执行退款流程");
        }
        //最后修改订单状态
        build.setPayStatus(Orders.REFUND);
        build.setCancelReason("用户取消");
        build.setCancelTime(LocalDateTime.now());
        //最后进行更新
        orderMapper.update(build);
    }

    @Override
    public void getRepetition(Long id) {
        //根据订单id查订单详情页
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        //遍历复制将其copy到shoppingCart
        ShoppingCart shoppingCart=new ShoppingCart();
        for (OrderDetail orderDetail : orderDetailList) {
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            //补充完整
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            //完成插入
            shoppingMapper.insert(shoppingCart);
        }

    }

    @Override
    public PageResult getConditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //调用PageHelper插件
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //调用函数
        Page<OrderVO> p=orderMapper.getBuyUserId(ordersPageQueryDTO);
        //
        String orderDishesDes = "";
        for (OrderVO orderVO : p) {
            List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(orderVO.getId());
            for (OrderDetail orderDetail : byOrderId) {
                orderDishesDes=orderDishesDes+orderDetail.getName()+"*"+orderDetail.getNumber()+";";
            }
            orderVO.setOrderDishes(orderDishesDes);
            orderDishesDes="";
        }
        return new PageResult(p.getTotal(),p.getResult());

    }

    @Override
    public OrderStatisticsVO getStatistics() {
        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        //先查询待排送数量
        orderStatisticsVO.setConfirmed(orderMapper.count(Orders.CONFIRMED));
        //在查询派送中数量
        orderStatisticsVO.setDeliveryInProgress(orderMapper.count(Orders.DELIVERY_IN_PROGRESS));
        //最后查询待接单的数量
        orderStatisticsVO.setToBeConfirmed(orderMapper.count(Orders.TO_BE_CONFIRMED));
        return orderStatisticsVO;
    }

    @Override
    public void confirmOrders(Orders orders) {
        //接单就是修改status
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    @Override
    public void rejectionOrders(Orders orders) {
        //退款

        //然后修改订单信息
        orders.setPayStatus(Orders.REFUND);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void shopCancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersCancelDTO,orders);
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        //执行退款
        orders.setPayStatus(Orders.REFUND);
        orderMapper.update(orders);
    }

    @Override
    public void delivery(Long id) {
        Orders orders = Orders.builder().id(id).status(Orders.DELIVERY_IN_PROGRESS).build();
        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        Orders orders = Orders.builder().id(id).status(Orders.COMPLETED).deliveryTime(LocalDateTime.now()).build();
        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        OrderVO orderVO = orderMapper.getId(id);
        if(orderVO==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("type",2);//2代表催单
        map.put("orderId",id);
        map.put("content","订单号："+orderVO.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


}
